﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bussiness;
using System.Data;

namespace EWebsite.Admin.Feedback {
    public partial class Detail : System.Web.UI.Page {
        private DataTable _tblHistory;

        protected DataTable TblHistory {
            get { return _tblHistory; }
            set { _tblHistory = value; }
        }

        protected void Page_Load(object sender, EventArgs e) {
            
            int trans_id = 0;
            _tblHistory = new DataTable();
            try {
                trans_id = int.Parse(Request["id"]);
            }
            catch (Exception ex) {
                return;
            }


            if (!IsPostBack) {
                try {
                    panelPeding.Visible = false;

                    //panelB2.Visible = false;
                    //panelB4.Visible = false;
                    //panelB5.Visible = false;


                    TransactionBuss buss = new TransactionBuss();
                    DataTable table = buss.getDetail(trans_id);

                    lblID.Text = trans_id.ToString();
                    lblAddress.Text = table.Rows[0]["Address"].ToString();
                    lblBeginTransDate.Text = table.Rows[0]["BeginDate"].ToString();
                    lblEmail.Text = table.Rows[0]["Email"].ToString();
                    lblEndTransDate.Text = table.Rows[0]["EndDate"].ToString();
                    lblMinQuanlity.Text = table.Rows[0]["MinQuanlity"].ToString();
                    lblNextTransQuantity.Text = table.Rows[0]["NextTransQuanlity"].ToString();
                    lblPartnerID.Text = table.Rows[0]["PartnerID"].ToString();
                    lblPartnerName.Text = table.Rows[0]["Name"].ToString();
                    lblProduct.Text = table.Rows[0]["ProductName"].ToString();
                    lblProductID.Text = table.Rows[0]["ProductID"].ToString();
                    lblRegisterDay.Text = table.Rows[0]["RegisterDate"].ToString();
                    lblSessionID.Text = table.Rows[0]["SID"].ToString();
                    lblTel.Text = table.Rows[0]["Tel"].ToString();
                    lblTransID.Text = table.Rows[0]["TransID"].ToString();
                    lblWeight.Text = table.Rows[0]["Weight"].ToString();
                    lblWidth.Text = table.Rows[0]["Width"].ToString();
                    lblLength.Text = table.Rows[0]["Length"].ToString();
                    lblHeight.Text = table.Rows[0]["Height"].ToString();
                    lblPrice.Text = table.Rows[0]["ProductPrice"].ToString();

                    if (table.Rows[0]["State"].ToString().Equals("0")) {
                        panelPeding.Visible = true;
                        panel2.Visible = false;
                    }else if(table.Rows[0]["State"].ToString().Equals("2")){
                        panelPeding.Visible = false;
                        panel2.Visible = false;
                    }
                    else {
                        panel2.Visible = true;
                        panelPeding.Visible = false;
                        
                        //get citylist
                        //object obj = WSProxy.CallWebService("carrier ws link", "name ws", "WSLogin", new object[]{});
                        
                        DataTable cityList = CallWS.citiesList();

                        drpFromCity.DataTextField = "CityName";
                        drpFromCity.DataValueField = "CityID";
                        drpFromCity.DataSource = cityList;
                        drpFromCity.DataBind();

                        drpToCity.DataTextField = "CityName";
                        drpToCity.DataValueField = "CityID";
                        drpToCity.DataSource = cityList;
                        drpToCity.DataBind();

                        //load transaction history
                        TransactionBuss buss2 = new TransactionBuss();
                        _tblHistory = buss2.detailList(trans_id);
                        grvHistory.DataSource = _tblHistory;
                        grvHistory.DataBind();
                    }
                }
                catch (Exception ex) {
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e) {
            //get partner detail
            int id = int.Parse(Request["id"]); //transaction id
            
            //get datatable partner (link ws...)
            DataTable tblPartner = (new TransactionBuss()).getPartnerByTransID(id);

            String nameWS = tblPartner.Rows[0]["WS_Name"].ToString(); //name asmx class
            String linkWS_Login = tblPartner.Rows[0]["LinkWS_Login"].ToString();
            String linkWS_RefuseTrans = tblPartner.Rows[0]["LinkWS_RefuseTrans"].ToString();
            String pvdID = tblPartner.Rows[0]["PvdID"].ToString().Trim();
            String pvdPwd = tblPartner.Rows[0]["pvdPwd"].ToString().Trim();
            //login
            String SID = CallWS.loginPartner(linkWS_Login, nameWS, pvdID, pvdPwd);
            
            //call ws refuse
            //get transID
            String transID = lblTransID.Text;            
            String result = CallWS.refuseTrans(linkWS_RefuseTrans, nameWS, SID, transID);
            
            if (result.Equals("0")) { //success
                Response.Write("<script>alert('cancel transaction successfully')</script>");
            }
            else {
                Response.Write("<script>alert('cancel transaction error')</script>");
            }

            //update state = 2
            TransactionBuss transBuss = new TransactionBuss();
            transBuss.UpdateTransactionState(id, 2);
        }

        protected void btnAccept_Click(object sender, EventArgs e) {
            int id = int.Parse(lblID.Text);
            
            //get datatable partner (link ws...)
            int partnerID = int.Parse(lblPartnerID.Text);
            DataTable tblPartner = (new PartnerBuss()).getPartner(partnerID);

            String nameWS = tblPartner.Rows[0]["WS_Name"].ToString(); //name asmx class
            String linkWS_Login = tblPartner.Rows[0]["LinkWS_Login"].ToString();
            String linkWS_AcceptTrans = tblPartner.Rows[0]["LinkWS_RefuseTrans"].ToString();
            String pvdID = tblPartner.Rows[0]["PvdID"].ToString();
            String pvdPwd = tblPartner.Rows[0]["PvdPwd"].ToString();
            //login
            String SID = CallWS.loginPartner(linkWS_Login, nameWS, pvdID, pvdPwd);

            //call ws accept
            //get transID
            String transID = lblTransID.Text;
            String result = CallWS.acceptTrans(linkWS_AcceptTrans, nameWS, SID, transID);
            
            //String result = "0";
            if (result.Equals("0")) { //accept successfully
                //change status
               (new TransactionBuss()).UpdateTransactionState(id, 1);

                //show hide panel
                panelPeding.Visible = false;
                panel2.Visible = true;

                //get citylist
                //object obj = WSProxy.CallWebService("carrier ws link", "name ws", "WSLogin", new object[]{});
                DataTable cityList = CallWS.citiesList();

                drpFromCity.DataTextField = "CityName";
                drpFromCity.DataValueField = "CityID";
                drpFromCity.DataSource = cityList;
                drpFromCity.DataBind();

                drpToCity.DataTextField = "CityName";
                drpToCity.DataValueField = "CityID";
                drpToCity.DataSource = cityList;
                drpToCity.DataBind();
            }
            else { //error
                //(new TransactionBuss()).UpdateTransactionState(id, 3);
                Response.Write("<script>alert('Chấp nhận thất bại')</script>");
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e) {
           
            //get partner detail
            int transaction_id = int.Parse(Request["id"]); //transaction id

            String transID = lblTransID.Text; //Partner Transaction ID
            //get datatable partner (link ws...)
            DataTable tblPartner = (new TransactionBuss()).getPartnerByTransID(transaction_id);

            String nameWS = tblPartner.Rows[0]["WS_Name"].ToString(); //name asmx class
            String linkWS_Login = tblPartner.Rows[0]["LinkWS_Login"].ToString();
            String linkWS_CheckInventory = tblPartner.Rows[0]["LinkWS_CheckInventory"].ToString();
            String linkWS_UpdateInventory = tblPartner.Rows[0]["LinkWS_UpdateInventory"].ToString();
            String pvdID = tblPartner.Rows[0]["PvdID"].ToString().Trim();
            String pvdPwd = tblPartner.Rows[0]["PvdPwd"].ToString().Trim();
            //login                
            String SID_partner = CallWS.loginPartner(linkWS_Login, nameWS, pvdID, pvdPwd); //login partner ws

            //if login successful
            if (!SID_partner.Equals("-1")) {
                //update inventory
                float pricePerUnit = float.Parse(lblPrice.Text);
                float transPrice = float.Parse(lblTransPrice.Text);
                int addedQuantity = int.Parse(lblInventory.Text);
                float totalPrice = pricePerUnit * addedQuantity + transPrice;
                string routeLink = lblLink.Text;
                
                string result = CallWS.updateInventory(linkWS_UpdateInventory, nameWS, SID_partner, transID, addedQuantity, pricePerUnit, transPrice, totalPrice, routeLink);
                if (result.Equals("0")) { //update success
                    //save detail to db
                    Response.Write("<script>alert('cap nhat thanh cong');</script>");
                }
                else {
                    Response.Write("<script>alert('cap nhat that bai');</script>");
                }
            }

        }

        protected void btnCalPrice_Click(object sender, EventArgs e) {
            try {
                int updateQuantity = int.Parse(lblInventory.Text);

                float length = float.Parse(lblLength.Text);
                float width = float.Parse(lblWidth.Text);
                float height = float.Parse(lblHeight.Text) * updateQuantity;
                float weight = float.Parse(lblWeight.Text) * updateQuantity;
                float price = float.Parse(lblPrice.Text);
                String dimession = length + "|" + width + "|" + height + "|" + weight;

                String fromCity = drpFromCity.SelectedValue;
                String toCity = drpToCity.SelectedValue;

                //calc route price
                int transportType = int.Parse(drpTransportType.SelectedValue);
                float routePrice = CallWS.routePrice(fromCity, toCity, dimession, transportType);

                lblTransPrice.Text = routePrice.ToString();
            }
            catch (Exception ex) {
                return;
            }
        }

        /// <summary>
        /// check inventory
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e) {
            //check datetime
            DateTime endTransDate = DateTime.Parse(lblEndTransDate.Text);
            if (DateTime.Now > endTransDate) { //if !expire
                lblInventory.Text = "het han giao dich";
                return;
            }

            //check inventory
            if (checkInventory() > 0) {
                lblInventory.Text = checkInventory().ToString();
                panelB2.Visible = true;
                return;
            }
            else {
                lblInventory.Text = "that bai";
                return;
            }

        }

        private int checkInventory() {
            
            //get datatable partner (link ws...)
            int partnerID = int.Parse(lblPartnerID.Text);
            DataTable tblPartner = (new PartnerBuss()).getPartner(partnerID);

            String nameWS = tblPartner.Rows[0]["WS_Name"].ToString(); //name asmx class
            String linkWS_Login = tblPartner.Rows[0]["LinkWS_Login"].ToString();
            String linkWS_CheckInventory = tblPartner.Rows[0]["LinkWS_CheckInventory"].ToString();
            String pvdID = tblPartner.Rows[0]["PvdID"].ToString();
            String pvdPwd = tblPartner.Rows[0]["PvdPwd"].ToString();
            //login
            String SID = CallWS.loginPartner(linkWS_Login, nameWS, pvdID, pvdPwd);

            //call ws accept
            //get transID
            String transID = lblTransID.Text;
            //int result = CallWS.acceptTrans(linkWS_CheckInventory, nameWS, SID, transID);
            int result = CallWS.checkInventory(linkWS_CheckInventory, nameWS, SID, transID.Trim());
            return result;
        }

        #region "bind datatable"
        protected String bindTransportType(String type) {
            if(type.Equals("0"))
                return "Bình thường";
            else
                return "Vận chuyển nhanh bằng máy bay";
        }

        protected String bindCarrierInfo(String info) {
            string[] args = info.Split('|');
            try {
                String html = "<span class=\"lbl\"><label>Mã vận chuyển: </label>{0}</span>";
                html += "<span class=\"lbl\"><label>Giá vận chuyển: </label>{1}</span>";
                html += "<span class=\"lbl\"><label>Ngày đi dự kiến: </label>{2}</span>";
                html += "<span class=\"lbl\"><label>Ngày đến dự kiến: </label>{3}</span>";
                html += "<span class=\"lbl\"><label>Link theo dõi vận chuyển:</label><a href=\"{4}\">click</a></span>";
                return String.Format(html, args[0], args[1], args[2], args[3], args[4]); 
            }
            catch (Exception ex) { return ""; }            
        }
        #endregion
        /// <summary>
        /// dat hang van chuyen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e) {
            
            int updateQuantity = int.Parse(lblMinQuanlity.Text);

            //cal transport price
            float length = float.Parse(lblLength.Text);
            float width = float.Parse(lblWidth.Text);
            float height = float.Parse(lblHeight.Text) * updateQuantity;
            float weight = float.Parse(lblWeight.Text) * updateQuantity;
            float price = float.Parse(lblPrice.Text);
            String dimession = length + "|" + width + "|" + height + "|" + weight;

            String fromCity = drpFromCity.SelectedValue;
            String toCity = drpToCity.SelectedValue;

            //calc route price
            int transportType = int.Parse(drpTransportType.SelectedValue);
            //float routePrice = CallWS.routePrice(fromCity, toCity, dimession, transportType);

            String SID = CallWS.loginCarrier();
            String strResult = CallWS.routePrice2(SID, fromCity, toCity, transportType, dimession, Calendar1.SelectedDate);
            if (strResult.Equals("-1")) {
                lblTransPrice.Text = "khong tin thay ngay phu hop";

            }
            else if (strResult.Equals("0")) {
                lblTransPrice.Text = "tu choi van chuyen";
            }
            else {
                //save to db
                int transaction_id = int.Parse(Request["id"]); //transaction id
                TransactionDetailBuss detailBuss = new TransactionDetailBuss();
                detailBuss.add(transaction_id, transportType, price, strResult, updateQuantity); //save to db

                string[] strArr = strResult.Split('|');

                lblTransPrice.Text = strArr[1];
                lblLink.Text = strArr[4];
                //panelB5.Visible = true;
            }
        }

        protected void btnTranferMoney_Click(object sender, EventArgs e) {
            CarrierBuss buss = new CarrierBuss();
            DataTable tbl = buss.getCarriers();
            String creditCardNumber = tbl.Rows[0]["CreditCardNumber"].ToString().Trim();
            String creditCardHolderName = tbl.Rows[0]["CardHolderName"].ToString().Trim();
            String creditCardSecureNum = tbl.Rows[0]["CardSecureNum"].ToString().Trim();
            String SID = CallWS.loginBroker();
            if(!SID.Equals("-1")){
                int result = CallWS.tranferMoneyForProvider(SID, creditCardNumber, float.Parse(lblTransPrice.Text), creditCardSecureNum, creditCardHolderName);
                if (result == 0) {
                    Response.Write("<script>alert('chuyen tien thanh cong');</script>");
                }
                else {
                    Response.Write("<script>alert('chuyen tien that bai');</script>");
                }
            }
        }
    }
}